from fastapi import APIRouter, Depends
from typing import List
from backend.core.heartbeat import get_all_clients_status, update_client_heartbeat
from backend.db.database import get_db
from sqlalchemy.orm import Session
from backend.db.models import Client

router = APIRouter(prefix="/api/clients", tags=["clients"])


# 获取所有客户端状态
@router.get("/")
def get_clients():
    """获取所有客户端的在线状态、最后心跳时间等信息"""
    return get_all_clients_status()


# 获取单个客户端信息
@router.get("/{client_id}")
def get_client(client_id: str, db: Session = Depends(get_db)):
    """获取指定客户端的详细信息"""
    client = db.query(Client).filter(Client.client_id == client_id).first()
    if not client:
        return {"error": "客户端不存在"}

    return {
        "client_id": client.client_id,
        "client_name": client.client_name,
        "client_type": client.client_type,
        "last_heartbeat": client.last_heartbeat.isoformat() if client.last_heartbeat else None,
        "is_online": client.is_online,
        "created_at": client.created_at.isoformat()
    }


# 手动更新客户端状态（用于测试）
@router.post("/{client_id}/heartbeat")
def manual_heartbeat(
        client_id: str,
        client_name: str = "test-client",
        client_type: str = "unknown"
):
    """手动发送客户端心跳（主要用于测试）"""
    update_client_heartbeat(client_id, client_name, client_type)
    return {"message": "心跳已更新"}
